package com.zyp.jobseeker.config;
import com.zyp.jobseeker.entity.User;
import com.zyp.jobseeker.filter.JwtAuthenticationFilter;
import com.zyp.jobseeker.service.UserService;
import com.zyp.jobseeker.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.config.annotation.ObjectPostProcessor;

/**
 * 安全配置类 - 管理Spring Security核心配置
 * 包含JWT认证、安全上下文管理和API权限控制
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    /**
     * 安全过滤链配置
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 添加安全过滤链开始处理日志
        System.out.println("[Security Config] 🔁 开始构建安全过滤链");
        
        http
            // 禁用CSRF保护（适配Spring Security 6.x）
            .csrf(csrf -> csrf.disable())
            // 使用无状态会话管理
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            // 配置权限规则
            .authorizeHttpRequests(auth -> auth
                // 增强路径匹配日志
                .requestMatchers(request -> {
                    String path = request.getRequestURI();
                    boolean isMatched = "/api/login".equals(path) ||
                                   "/api/register/student".equals(path) ||
                                   "/api/register/enterprise".equals(path) ||
                                   "/api/error".equals(path)||
                                    "/api/ping".equals(path);
                    
                    // 添加路径匹配日志（使用统一日志格式）
                    System.out.println("[Security Config] 🔍 Matching path: " + path + ", Matched: " + isMatched);
                    return isMatched;
                }).permitAll()
                // 其他请求需要认证
                .anyRequest().authenticated()
            )
            // 添加JWT过滤器 - 应该在UsernamePasswordAuthenticationFilter之前
            .addFilterBefore(new JwtAuthenticationFilter(jwtUtil, userDetailsService()), 
                           UsernamePasswordAuthenticationFilter.class)
            ;

        // 添加安全过滤链构建完成日志
        System.out.println("[Security Config] ✅ 安全过滤链构建完成");
            
        return http.build();
    }

    /**
     * 认证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

//    /**
//     * 用户详情服务
//     */
//    @Bean
//    public UserDetailsService userDetailsService() {
//        return username -> {
//            // 从数据库获取用户信息
//            User user = userService.findByUsername(username);
//            if (user == null) {
//                throw new RuntimeException("用户不存在");
//            }
//            return new org.springframework.security.core.userdetails.User(
//                    user.getUsername(),
//                    user.getPassword(),
//                    user.isEnabled(),
//                    true, // isCredentialsNonExpired
//                    true, // isAccountNonExpired
//                    user.isAccountNonLocked(),
//                    user.getAuthorities()
//            );
//        };
//    }
    /**
     * 用户详情服务
     */
    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            System.out.println("[Security Config] 🔍 加载用户详情: " + username);
            User user = userService.findByUsername(username);
            if (user == null) {
                System.out.println("[Security Config] ❌ 用户不存在: " + username);
                throw new RuntimeException("用户不存在");
            }
            System.out.println("[Security Config] ✅ 加载用户成功: " + username + ", 角色: " + user.getRole());
            return user; // 直接返回已实现UserDetails接口的User实体
        };
    }

    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        // 配置默认密码编码器
        return new BCryptPasswordEncoder();
    }

    /**
     * 忽略特定路径的安全检查
     */
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return web -> web.ignoring().requestMatchers("/v2/api-docs/**",
                "/swagger-resources/**",
                "/swagger-ui.html",
                "/webjars/**");
    }
}